using System.Text;
using System.Text.Json;
using Vin.Tool.Core.AssertCategory;

namespace Vin.Tool.Core.StreamCategory;

public class StreamTool
{
    public static async Task<string> ReadToString(Stream stream, Encoding? encoding = null)
    {
        encoding ??= Encoding.UTF8;
        if (!stream.CanRead) return "";
        if (stream.CanSeek) stream.Seek(0, SeekOrigin.Begin);
        var reader = new StreamReader(stream, encoding);
        var data = await reader.ReadToEndAsync();
        if (stream.CanSeek)
        {
            stream.Seek(0, SeekOrigin.Begin);
            stream.Position = 0;
        }
        return data;
    }

    public static async Task<JsonElement?> ReadToJson(Stream stream, Encoding? encoding = null)
    {
        var json = await ReadToString(stream, encoding);
        if (json.IsNullOrEmpty()) return null;
        return JsonDocument.Parse(json).RootElement;
    }

    public static async Task<T?> ReadToJson<T>(Stream stream, Encoding? encoding = null)
    {
        var json = await ReadToString(stream, encoding);
        if (json.IsNullOrEmpty()) return default;
        return JsonSerializer.Deserialize<T>(json);
    }
}